﻿using Furion;
using Furion.SpecificationDocument;
using GoViewServer.Core;
using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.IO;

namespace GoViewServer.Web.Core;

public class Startup : AppStartup
{
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddCorsAccessor();

        services.AddEventBus();

        services.AddSqlsugarSetup(App.Configuration);

        services.AddJwt();

        services.AddFileLogging("logs/info/{0:yyyy}-{0:MM}-{0:dd}.log", options =>
        {
            options.FileNameRule = fileName =>
            {
                return string.Format(fileName, System.DateTime.Now);
            };
            options.WriteFilter = (logMsg) =>
            {
                return logMsg.LogLevel == LogLevel.Information;
            };
        });

        services.AddFileLogging("logs/error/{0:yyyy}-{0:MM}-{0:dd}.log", options =>
        {
            options.FileNameRule = fileName =>
            {
                return string.Format(fileName, System.DateTime.Now);
            };
            options.WriteFilter = (logMsg) =>
            {
                return logMsg.LogLevel == LogLevel.Error;
            };
        });

        //services.AddDatabaseLogging<DatabaseLoggingWriter>(options =>
        //{
        //    options.MinimumLevel = LogLevel.Information;
        //});

        services.AddConsoleFormatter(options =>
        {
            options.WriteHandler = (logMsg, scopeProvider, writer, fmtMsg, opt) =>
            {
                writer.WriteLine(fmtMsg);
            };
        });

        //services.AddMonitorLogging();

        services.AddControllersWithViews()
            .AddJsonOptions(options => {
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
            })
         .AddNewtonsoftJson(options =>
         {
             options.SerializerSettings.ContractResolver = new DefaultContractResolver();
             options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
             options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
         })
                .AddInjectWithUnifyResult<RESTfulResultProvider>();
    }

    public   void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        if (!Directory.Exists("oss"))
        {
            Directory.CreateDirectory("oss");
        }

        if (!Directory.Exists("wwwroot"))
        {
            Directory.CreateDirectory("wwwroot");
        }

        app.UseStaticFiles(new StaticFileOptions()
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "oss")),
            RequestPath = "/oss"
        });

        app.UseStaticFiles(new StaticFileOptions()
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")),
            RequestPath = ""
        });


        app.UseFileServer();

        app.UseUnifyResultStatusCodes();

        app.UseCorsAccessor();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseKnife4UI(options =>
        {
            options.RoutePrefix = "newapi";  // 配置 Knife4UI 路由地址，现在是 /newapi
            foreach (var groupInfo in SpecificationDocumentBuilder.GetOpenApiGroups())
            {
                options.SwaggerEndpoint("/" + groupInfo.RouteTemplate, groupInfo.Title);
            }
        });
        app.UseInject();

        app.UseInject(string.Empty);


        app.UseEndpoints(endpoints =>
        {
            // 注册集线器
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });



    }
}

